package org.example.StudentManagementSystem.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/file")
@CrossOrigin(origins = "*")
public class FileController {

    @Value("${file.upload-dir}")
    private String uploadDir;

    /**
     * 获取头像
     *
     * @param filename 文件名
     * @return 包含头像文件的响应实体
     */
    @Operation(summary = "获取头像", description = "根据文件名获取头像图片")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "成功获取头像",
                    content = { @Content(mediaType = "image/*",
                            schema = @Schema(type = "string", format = "binary")) }),
            @ApiResponse(responseCode = "404", description = "头像文件不存在或不可读",
                    content = { @Content() }),
            @ApiResponse(responseCode = "500", description = "内部服务器错误",
                    content = { @Content() })
    })
    @GetMapping("/avatar/{filename:.+}")
    public ResponseEntity<Resource> getAvatar(
            @Parameter(in = ParameterIn.PATH, description = "头像文件名", required = true)
            @PathVariable String filename) {
        try {
            // 构建文件路径
            Path filePath = Paths.get(uploadDir, filename).normalize();
            Resource resource = new FileSystemResource(filePath.toFile());

            if (!resource.exists() || !resource.isReadable()) {
                return ResponseEntity.notFound().build();
            }

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            String encodedFilename = URLEncoder.encode(resource.getFilename(), "UTF-8");
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + encodedFilename + "\"");

            // 判断文件类型
            String contentType = URLConnection.guessContentTypeFromName(resource.getFilename());
            if (contentType == null) {
                contentType = "application/octet-stream";
            }
            // 返回文件内容
            return ResponseEntity.ok().headers(headers).contentType(MediaType.parseMediaType(contentType)) // 根据实际情况调整媒体类型
                    .body(resource);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }
}
